﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LIB
{
    public class pager
    {

        /// <summary>
        /// 显示分页导航
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="totalRecord">总记录数</param>
        /// <param name="pageSize">每页记录条数</param>
        /// <returns>分页导航的html代码</returns>
        public static string getPageHtml(System.Web.UI.Page page, int totalRecord, int pageSize)
        {
            int currentPage = 1;
            try { currentPage = int.Parse(page.Request.QueryString["p"]); }
            catch { }
            if (currentPage < 1) currentPage = 1;
            int lastPage = (int)((double)(totalRecord-1) / (double)pageSize) + 1;
            if (currentPage > lastPage) currentPage = lastPage;

            string Url = page.Request.Url.ToString();
            //string u = setPageUrl(Url, currentPage);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //sb.Append("total=" + totalRecord.ToString() + ",pageszie=" + pageSize.ToString());
            sb.Append("<span class=\"spnPager\">");
            if (currentPage == 1) sb.Append("首页&nbsp;上一页&nbsp;");
            else sb.Append("<a href='" + setPageUrl(Url, 1) + "'>首页</a>&nbsp;<a href='" +  setPageUrl(Url, currentPage - 1) + "'>上一页</a>&nbsp;");

            if (currentPage == lastPage) sb.Append("尾页&nbsp;下一页&nbsp;");
            else sb.Append("<a href='" + setPageUrl(Url, 1) + "'>尾页</a>&nbsp;<a href='" + setPageUrl(Url, currentPage + 1) + "'>下一页</a>&nbsp;");

            sb.Append(" 共" + lastPage.ToString() + "页，当前是第" + currentPage.ToString() + "页 ");
            sb.Append("</span>");
            return sb.ToString();
        }

        private static string setPageUrl(string url, int p)
        {
            string rtn = url;
            if (url.IndexOf("&p=") > 0) rtn = System.Text.RegularExpressions.Regex.Replace(url, @"(\&)?p=(\d)+", "&p=" + p.ToString());
            else if (url.IndexOf("?p=") > 0) rtn = System.Text.RegularExpressions.Regex.Replace(url, @"(\&)?p=(\d)+", "p=" + p.ToString());
            else if (url.IndexOf("?") > 0) rtn += "&p=" + p.ToString();
            else rtn += "?p=" + p.ToString();
            return rtn;
        }


    }
}
